﻿using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Organizations;
using Abp.UI;
using Camc.Quality.Authorization.Roles;
using Camc.Quality.Bop;
using Camc.Quality.Common;
using Camc.Quality.WorkFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static Camc.Quality.Inspection.InspectionSeverityDesc;

namespace Camc.Quality.Inspection
{
    public class InspectionModelAppService : QualityAppServiceBase
    {
        private readonly IRepository<InspectionSeverityDesc, Guid> _inspectionSeverityDescRepository;
        private readonly IRepository<InspectionSeverityRole, Guid> _inspectionSeverityRoleRepository;
        private readonly IRepository<InspectionTypeDesc, Guid> _inspectionTypeDescRepository;
        private readonly IRepository<InspectionItemInfo, Guid> _inspectionItemInfoRepository;
        private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository;
        private readonly RoleManager _roleManager;
        private readonly WorkFlowAppService _workFlowAppServiceRepository;
        private readonly IRepository<AffairRemind, int> _affairRemindRepository;
        private readonly IRepository<InspectionStandardDesc, Guid> _inspectionStandardDescRepository;

        public InspectionModelAppService(IRepository<InspectionSeverityDesc, Guid> inspectionSeverityDescRepository,
                                         IRepository<InspectionSeverityRole, Guid> inspectionSeverityRoleRepository,
                                         IRepository<InspectionTypeDesc, Guid> inspectionTypeDescRepository,
                                         IRepository<InspectionItemInfo, Guid> inspectionItemInfoRepository,
                                         IRepository<OrganizationUnit, long> organizationUnitRepository,
                                         RoleManager roleManager,
                                         WorkFlowAppService workFlowAppServiceRepository,
                                         IRepository<AffairRemind, int> affairRemindRepository,
                                         IRepository<InspectionStandardDesc, Guid> inspectionStandardDescRepository
            )
        {
            _inspectionSeverityDescRepository = inspectionSeverityDescRepository;
            _inspectionSeverityRoleRepository = inspectionSeverityRoleRepository;
            _inspectionTypeDescRepository = inspectionTypeDescRepository;
            _inspectionItemInfoRepository = inspectionItemInfoRepository;
            _organizationUnitRepository = organizationUnitRepository;
            _roleManager = roleManager;
            _workFlowAppServiceRepository = workFlowAppServiceRepository;
            _affairRemindRepository = affairRemindRepository;
            _inspectionStandardDescRepository = inspectionStandardDescRepository;
        }
        /// <summary>
        /// 角色下拉列表
        /// </summary>
        /// <returns></returns>
        public List<RoleNameListDto> GetRoleManagerNameList()
        {
            var nameList = _roleManager.Roles.ToList();
            if (nameList != null)
            {
                var roleNameListDto = ObjectMapper.Map<List<RoleNameListDto>>(nameList);
                return roleNameListDto;
            }
            else
            {
                throw new UserFriendlyException("") ;
            }
        }
        /// <summary>
        /// 部门下拉列表
        /// </summary>
        /// <returns></returns>
        public List<OrganizationUnitsListDto> GetOrganizationUnitsList()
        {
            var nameList = _organizationUnitRepository.GetAll();
            if (nameList != null)
            {
                var organizationUnitsListDto = ObjectMapper.Map<List<OrganizationUnitsListDto>>(nameList);
                return organizationUnitsListDto;
            }
            else
            {
                throw new UserFriendlyException("");
            }
        }
        /// <summary>
        /// 根据ID查询角色名
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GetRoleById(int id)
        {
            var role = _roleManager.Roles.FirstOrDefault(d => d.Id == id);
            if (role != null)
            {
                return role.DisplayName;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 根据ID查询部门名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private string GeOrganizationUnitsById(int id)
        {
            var role = _organizationUnitRepository.FirstOrDefault(d => d.Id == id);
            if (role != null)
            {
                return role.DisplayName;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        ///异常严重程度查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<InspectionSeverityDescOutDto>> GetInspectionSeverityDescList(GetInspectionSeverityDescInput input)
        {
            var severityDesc = from isd in _inspectionSeverityDescRepository.GetAll().Where(s => s.IsUsed != IsUseds.已删除)
                               join arr in _affairRemindRepository.GetAll()
                               on isd.Id.ToString() equals arr.AffairCode
                               select new InspectionSeverityDescOutDto
                               {
                                   Id = isd.Id,
                                   SeverityName = isd.SeverityName,
                                   SeverityDesc = isd.SeverityDesc,
                                   IsUsed = (int)isd.IsUsed,
                                   CCRole = arr.RoleListDesc,
                                   CreationTime = isd.CreationTime
                               };
            var count = severityDesc.Count();
            severityDesc = severityDesc.OrderByDescending(e => e.CreationTime).PageBy(input);
            return new PagedResultDto<InspectionSeverityDescOutDto>(count, severityDesc.ToList());
        }
        /// <summary>
        ///一级异常查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<InspectionTypeDescDto>> GetInspectionTypeDescList(GetInspectionTypeDescInput input)
        {
            var typeDescQuery = _inspectionTypeDescRepository.GetAll().Where(s=> s.IsUsed != InspectionTypeDesc.IsUseds.已删除);
            var count = typeDescQuery.Count();
            typeDescQuery = typeDescQuery.OrderByDescending(e => e.CreationTime).PageBy(input);
            var result = ObjectMapper.Map<List<InspectionTypeDescDto>>(typeDescQuery);
            return new PagedResultDto<InspectionTypeDescDto>(count, result);
        }
        /// <summary>
        /// 二级异常查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<InspectionItemInfoOutDto>> GetInspectionItemInfoList(GetInspectionItemInfoInput input)
        {
            var itemInfoQuery = from ii in _inspectionItemInfoRepository.GetAll().Where(s => s.IsUsed != InspectionItemInfo.IsUseds.已删除)
                                join itd in _inspectionTypeDescRepository.GetAll()
                                on ii.TypeId equals itd.Id
                                where itd.Id == input.TypeId
                                select ii;
            var count = itemInfoQuery.Count();
            itemInfoQuery = itemInfoQuery.OrderByDescending(e => e.CreationTime).PageBy(input);
            var result = ObjectMapper.Map<List<InspectionItemInfoOutDto>>(itemInfoQuery);
            result.ForEach(d =>
            {
                d.OrganizationUnits = GeOrganizationUnitsById(int.Parse(d.OrganizationUnitsId));
                d.Role = GetRoleById(int.Parse(d.RolesId));
            });
            return new PagedResultDto<InspectionItemInfoOutDto>(count, result);
        }
        /// <summary>
        /// 异常严重程度新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CreateOrUpdateInspectionSeverityDesc(InspectionSeverityDescDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            if (input.Id == Guid.Empty)
            {
                resultMessage = await CreateInspectionSeverityDesc(input);
            }
            else
            {
                resultMessage = await UpdateInspectionSeverityDesc(input);
            }
            return resultMessage;
        }
        /// <summary>
        /// 异常严重程度insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> CreateInspectionSeverityDesc(InspectionSeverityDescDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionSeverityDesc = new InspectionSeverityDesc()
                {
                    Id = Guid.NewGuid(),
                    SeverityName = input.SeverityName,
                    SeverityDesc = input.SeverityDesc,
                    IsUsed = (IsUseds)input.IsUsed
                };
                var workFlow = _affairRemindRepository.FirstOrDefault(s => s.AffairCode == inspectionSeverityDesc.Id.ToString());
                if (workFlow == null)
                {
                    var role = _roleManager.Roles.ToList();
                    AffairRemind temp = new AffairRemind();
                    temp.AffairCode = inspectionSeverityDesc.Id.ToString();
                    temp.AffairType = "异常管理";
                    temp.RoleList = string.Join(",", input.CCRole);
                    temp.RoleListDesc = string.Join(",", role.Where(s => temp.RoleList.Contains(s.Id.ToString())).Select(s => s.DisplayName));
                    temp.IsOpen = true;
                    temp.Isdefault = true;
                    _affairRemindRepository.Insert(temp);
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "数据错误，请检查数据库";
                    //return resultMessage;
                    //throw new UserFriendlyException("数据错误，请检查数据库");
                }
                //for (int i = 0; i < input.CCRole.Length; i++)
                //{
                //    var inspectionSeverityRole = new InspectionSeverityRole()
                //    {
                //        Id = Guid.NewGuid(),
                //        SeverityId = inspectionSeverityDesc.Id,
                //        RoleId = input.CCRole[i]
                //    };
                //    await _inspectionSeverityRoleRepository.InsertAsync(inspectionSeverityRole);
                //}
                await _inspectionSeverityDescRepository.InsertAndGetIdAsync(inspectionSeverityDesc);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 异常严重程度update
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> UpdateInspectionSeverityDesc(InspectionSeverityDescDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionSeverityDesc = await _inspectionSeverityDescRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
                if (inspectionSeverityDesc != null)
                {
                    inspectionSeverityDesc.SeverityName = input.SeverityName;
                    inspectionSeverityDesc.SeverityDesc = input.SeverityDesc;
                    inspectionSeverityDesc.IsUsed = (IsUseds)input.IsUsed;

                    await _inspectionSeverityDescRepository.UpdateAsync(inspectionSeverityDesc);
                }
                //await _inspectionSeverityRoleRepository.DeleteAsync(p => p.AffairCode == input.Id.ToString);
                var workFlow = _affairRemindRepository.FirstOrDefault(s => s.AffairCode == input.Id.ToString());
                if (workFlow != null)
                {
                    var role = _roleManager.Roles.ToList();
                    workFlow.RoleList = string.Join(",", input.CCRole);
                    workFlow.RoleListDesc = string.Join(",", role.Where(s => workFlow.RoleList.Contains(s.Id.ToString())).Select(s => s.DisplayName));
                    _affairRemindRepository.Update(workFlow);
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "数据错误，请检查数据库";
                    return resultMessage;
                    //throw new UserFriendlyException("数据错误，请检查数据库");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 一级异常新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CreateOrUpdateInspectionTypeDesc(InspectionTypeDescDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            if (input.Id == Guid.Empty)
            {
                resultMessage =await CreateInspectionTypeDesc(input);
            }
            else
            {
                resultMessage =await UpdateInspectionTypeDesc(input);
            }
            return resultMessage;
        }
        /// <summary>
        /// 一级异常insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> CreateInspectionTypeDesc(InspectionTypeDescDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionTypeDesc = new InspectionTypeDesc()
                {
                    Id = Guid.NewGuid(),
                    TypeName = input.TypeName,
                    IsUsed = (InspectionTypeDesc.IsUseds)(IsUseds)input.IsUsed
                };
                await _inspectionTypeDescRepository.InsertAndGetIdAsync(inspectionTypeDesc);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 一级异常update
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> UpdateInspectionTypeDesc(InspectionTypeDescDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionTypeDesc = await _inspectionTypeDescRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
                if (inspectionTypeDesc != null)
                {
                    inspectionTypeDesc.TypeName = input.TypeName;
                    inspectionTypeDesc.IsUsed = (InspectionTypeDesc.IsUseds)(IsUseds)input.IsUsed;

                    await _inspectionTypeDescRepository.UpdateAsync(inspectionTypeDesc);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 二级异常新增和修改接口，根据是否传输id判断
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CreateOrUpdateCreateInspectionItemInfo(InspectionItemInfoDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            if (input.Id == Guid.Empty)
            {
                resultMessage = await CreateInspectionItemInfo(input);
            }
            else
            {
                resultMessage = await UpdateInspectionItemInfo(input);
            }
            return resultMessage;
        }
        /// <summary>
        /// 二级异常insert
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> CreateInspectionItemInfo(InspectionItemInfoDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var InspectionItemInfo = new InspectionItemInfo()
                {
                    Id = Guid.NewGuid(),
                    TypeId = input.TypeId,
                    ItemName = input.ItemName,
                    OrganizationUnitsId = input.OrganizationUnitsId,
                    RolesId = input.RolesId,
                    IsUsed = (InspectionItemInfo.IsUseds)(IsUsed)input.IsUsed
                };
                await _inspectionItemInfoRepository.InsertAndGetIdAsync(InspectionItemInfo);
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 二级异常update
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ResultMessage> UpdateInspectionItemInfo(InspectionItemInfoDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionItemInfo = await _inspectionItemInfoRepository.FirstOrDefaultAsync(c => c.Id == input.Id);
                if (inspectionItemInfo != null)
                {
                    inspectionItemInfo.TypeId = input.TypeId;
                    inspectionItemInfo.ItemName = input.ItemName;
                    inspectionItemInfo.OrganizationUnitsId = input.OrganizationUnitsId;
                    inspectionItemInfo.RolesId = input.RolesId;
                    inspectionItemInfo.IsUsed = (InspectionItemInfo.IsUseds)(IsUsed)input.IsUsed;

                    await _inspectionItemInfoRepository.UpdateAsync(inspectionItemInfo);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 异常严重程度删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleteInspectionSeverityDesc(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionStardardDesc = _inspectionStandardDescRepository.GetAll().Where(s => s.InspectionSeverityDescId == id);
                if (inspectionStardardDesc.Count() > 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该异常严重程度已经被使用不能删除";
                    return resultMessage;
                    //throw new UserFriendlyException("该异常严重程度已经被使用不能删除");
                }
                var inspectionSeverityDesc = await _inspectionSeverityDescRepository.FirstOrDefaultAsync(c => c.Id == id);
                if (inspectionSeverityDesc != null)
                {
                    inspectionSeverityDesc.IsUsed = (IsUseds)2;
                    await _inspectionSeverityDescRepository.UpdateAsync(inspectionSeverityDesc);
                    var workFlow = _affairRemindRepository.FirstOrDefault(s => s.AffairCode == id.ToString());
                    if (workFlow != null)
                    {
                        await _affairRemindRepository.DeleteAsync(workFlow);
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
            //var inspectionSeverityRoles = _inspectionSeverityRoleRepository.GetAll().Where(s => s.SeverityId == id);
        }
        /// <summary>
        /// 一级异常删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleteInspectionTypeDesc(Guid id)
        {
                ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionStardardDesc = _inspectionStandardDescRepository.GetAll().Where(s => s.InspectionTypeDescId == id);
                if (inspectionStardardDesc.Count() > 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该一级异常已经被使用不能删除";
                    return resultMessage;
                    //throw new UserFriendlyException("该一级异常已经被使用不能删除");
                }
                var inspectionTypeDesc = await _inspectionTypeDescRepository.FirstOrDefaultAsync(p => p.Id == id);
                if (inspectionTypeDesc != null)
                {
                    inspectionTypeDesc.IsUsed = (InspectionTypeDesc.IsUseds)2;
                    await _inspectionTypeDescRepository.UpdateAsync(inspectionTypeDesc);
                }
                var inspectionItemInfo = await _inspectionItemInfoRepository.FirstOrDefaultAsync(p => p.TypeId == id);
                if (inspectionItemInfo != null)
                {
                    inspectionItemInfo.IsUsed = (InspectionItemInfo.IsUseds)2;
                    await _inspectionItemInfoRepository.UpdateAsync(inspectionItemInfo);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 二级异常删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleteInspectionItemInfo(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var inspectionStardardDesc = _inspectionStandardDescRepository.GetAll().Where(s => s.InspectionItemInfoId == id);
                if (inspectionStardardDesc.Count() > 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "该二级异常已经被使用不能删除";
                    return resultMessage;
                    //throw new UserFriendlyException("该二级异常已经被使用不能删除");
                }
                var inspectionItemInfo = await _inspectionItemInfoRepository.FirstOrDefaultAsync(c => c.Id == id);
                if (inspectionItemInfo != null)
                {
                    inspectionItemInfo.IsUsed = (InspectionItemInfo.IsUseds)2;
                    await _inspectionItemInfoRepository.UpdateAsync(inspectionItemInfo);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
    }
}
